<template>
  <el-dialog
    :title="!dataForm.roleId ? '新增' : '修改'"
    :visible.sync="visible"
    width="60%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="110px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="dataForm.title"
          clearable
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <MyEditor ref="editValue"></MyEditor>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import MyEditor from "@/components/MyEditor";
import { getDataInfo, savaDataInfo } from "@/api/guide";
export default {
  components: { MyEditor },
  data() {
    return {
      visible: false,
      dataForm: {
        content: "",
      },
      dataRule: {
        title: { required: true, message: "标题不能为空", trigger: "blur" },
      },
    };
  },
  mounted() {},
  methods: {
    init(id) {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs.editValue.editValue = "";
        this.$refs["dataForm"].resetFields();
        this.dataForm = { id };
        if (id) {
          getDataInfo(id)
            .then((data) => {
              if (data && data.code === 0) {
                this.dataForm = data.data;
                this.$refs.editValue.editValue = this.dataForm.content;
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.content = this.$refs.editValue.editValue;
          savaDataInfo(this.dataForm)
            .then((res) => {
              if (res && res.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },
  },
};
</script>
